using System;
using System.Globalization;

using Outcoder.UI.Xaml.Data;

namespace Outcoder.UI.Xaml
{
	/// <summary>
	/// Xamarin Forms does not support custom type conversion yet.
	/// This class is used to convert a string value to an object 
	/// whose type is defined using the supplied object parameter.
	/// </summary>
	public class StringToTypedObjectBaseConverter : IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			if (value == null)
			{
				return null;
			}

			string valueString = value.ToString();

			string typeString = parameter != null ? parameter.ToString() : null;

			if (typeString != null)
			{
				Type type = Type.GetType(typeString, false);

				if (type != null)
				{
					if (type == typeof(int))
					{
						return int.Parse(valueString);
					}

					if (type == typeof(double))
					{
						return double.Parse(valueString);
					}

					if (type == typeof(float))
					{
						return float.Parse(valueString);
					}

					if (type == typeof(Uri))
					{
						return new Uri(valueString);
					}

					var result = Activator.CreateInstance(type, new object[] {valueString});
					return result;
				}
			}

			return value;
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			throw new NotImplementedException();
		}
	}
}